package cn.micai.base.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述：使用线程池创建多线程程序
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/5/11 14:22
 */
public class MyThreadPool {

    public static void main(String [] args) {
        // 在线程池中创建2个线程 newFixedThreadPool创建一个可重用固定线程数的线程池，以共享的无界队列方式来运行这些线程
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 创建100个线程目标对象
        for (int index =0; index<100; index++) {
            Runnable run = new Runner(index);
            // 执行线程目标对象
            executorService.execute(run);
        }
        // shutdown
        executorService.shutdown();
    }

    static class Runner implements Runnable {
        int index = 0;
        public Runner(int index) {
            this.index = index;
        }
        @Override
        public void run() {
            long time = (long) (Math.random()*1000);
            // 输出线程的名字和使用目标对象及休眠的时间
            System.out.println("线程：" + Thread.currentThread().getName() + "(目标对象" + index + ")" + ":Sleeping " + time + "ms");
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


